<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="SOP" name="first">
        <el-container>
          <el-aside :style="{ width: sidebarWidth + 'px',display: 'block' }" ref="sidebar" class="resizable-sidebar">
            <!--            <div class="resize-handle" @mousedown="startResize"></div> 设置左右滑动  -->
            <div>
              <el-button v-if="sidebarVisible" class="el-icon-d-arrow-left hide-sidebar-icon"
                         type="primary" @click="hideSidebar"></el-button>
              <el-button v-else class="el-icon-d-arrow-right hide-sidebar-icon" type="primary"
                         @click="hideSidebar"></el-button>
              <el-button v-if="sidebarVisible" class="hide-sidebar-icon" type="primary"
                         @click="handleCarouselInfo"> {{ carouselInfo }}
              </el-button>
              <el-input v-if="sidebarVisible" v-model.number="carouselTime" style="width: 60px" type="text"
                        :value="carouselTime" :disabled="disabledVal"></el-input>
              <i v-if="sidebarVisible" style="margin-left: 5px">秒</i>
            </div>
            <div class="sidebar-header" v-if="sidebarVisible">
              <el-input class="el-input-filter" v-model="filterText" placeholder="过滤条件"
                        style="margin-left:10px;margin-right: 10px;margin-top:5px;height: 30px"/>
            </div>
            <div class="sidebar-tree-wrapper" v-if="sidebarVisible">
              <el-tree
                ref="tree2"
                :data="data2"
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
                style="margin-right: 5px"
              />
            </div>
          </el-aside>
          <el-main>
            <div class="pdf-container" :style="'height:' + height">
              <iframe :src="pdfUrl" width="100%" height="100%"></iframe>
            </div>
          </el-main>
        </el-container>
      </el-tab-pane>
      <el-tab-pane label="问题清单" name="second">
        <el-container>
          <el-header class="el-header-content">
            <div>
              <span class="el-header-container">{{ wipOrderNo }}</span>
              <span class="el-header-container">{{ productNo }}</span>
              <span class="el-header-container">{{ modelNo }}</span>
            </div>
          </el-header>
          <el-main class="el-main-header" >
            <el-form :model="form" label-width="0px" class = 'problem-form'>
              <div v-for="(item, index) in backendData" :key="index" class="problem-content">
                <div class = "problem-leftContent">
                <el-form-item >
                  <label class="custom-label">问题描述{{ index + 1 }}</label>
                  <div class="label-container">
                    <div class="text-content">{{ item.description }}</div>
                  </div>
                </el-form-item>
                <el-form-item >
                  <label class="custom-label">注意事项{{ index + 1 }}</label>
                  <div class="label-container">
                    <div class="text-content">{{ item.note }}</div>
                  </div>
                </el-form-item>
                </div>
                <div style="background-color: #ffffff;width: 10px">
                </div>
                <div style="margin-left: 15px;width: 75%" >
                <el-form-item v-if="item.imageUrl !== ''">
                  <div class="label-container">
                    <el-image
                      class="image-content"
                      :src="item.imageUrl"
                      :preview-src-list="item.imageUrlList"
                      fit="fill"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-loading"></i>
                      </div>
                    </el-image>
                  </div>
                </el-form-item>
                </div>
              </div>
            </el-form>
          </el-main>
        </el-container>
      </el-tab-pane>
      <el-tab-pane label="layout图" name="third">
        <el-container>
          <el-aside  ref="sidebar" class="resizable-sidebar">
            <div class="sidebar-header">
              <el-input class="el-input-filter" v-model="LayoutFilterText" placeholder="过滤条件"
                        style="margin-left:10px;margin-right: 10px;margin-top:5px;height: 30px"/>
            </div>
            <div class="sidebar-tree-wrapper">
              <el-tree
                ref="LayoutTree"
                :data="layoutData"
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleLayoutNodeClick"
                style="margin-right: 5px"
              />
            </div>
          </el-aside>
          <el-main>
            <div class="pdf-container" :style="'height:' + height">
              <iframe :src="layoutUrl" width="100%" height="100%"></iframe>
            </div>
          </el-main>
        </el-container>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {getFileInfo, getFileToken, getFileUrl, getSopAndProblemList} from '@/api/sop'

export default {
  data() {
    return {
      sidebarWidth: 300, // 侧边栏的初始宽度
      sidebarVisible: true, // 控制侧边栏的显示状态
      startX: 0, // 用于记录鼠标开始拖动时的位置
      resizing: false, // 是否正在拖动调整宽度
      height: document.documentElement.clientHeight - 180 + 'px',
      carouselInfo: '开启轮播',
      isCarousel: true,
      disabledVal: false,
      carouselTime: 30,
      filterText: '',
      LayoutFilterText: '',
      data2: [],
      layoutData:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      filecodes: [],
      pdfUrl: '',
      layoutUrl: '',
      activeName: 'first',
      form: {
        description: '',
        note: '',
        remarks: ''
      },
      backendData: [],
      wipOrderNo: '',
      productNo: '',
      modelNo: '',
      intervalId: null,
      initialized: false,
      storageCount: 0,
      appValue: '',
      tempFilecode: '',
      tempLayoutUrl: '',
      handleProblemStatus: true,
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    },
    LayoutFilterText(val) {
      this.$refs.LayoutTree.filter(val)
    },
  },
  mounted() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px'
    }
  },
  created() {
    //this.handleData()
    this.getSopProblemAndLayoutInfo()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) { //处理SOP
      if (data.filecode !== undefined && data.filecode !== this.tempFilecode) {
        this.tempFilecode = data.filecode
        this.getFileUrlSync(data.filecode)
      }
    },
    handleLayoutNodeClick(data) { //处理layout图
      if (data.fileUrl !== undefined && data.fileUrl !== this.tempLayoutUrl) {
        this.tempLayoutUrl = data.fileUrl
        this.getLayoutUrlSync(data.fileUrl)
      }
    },
    async handleClick(tab, event) { //处理图片
      if (tab.name === 'second' && this.handleProblemStatus) {
        const storage = window.localStorage;
        const tempToken = storage.getItem('access_token');
        await this.handleToken(tempToken);
        this.backendData.forEach(item => {
          if (item.imagePath !== '') {
            this.getProblemImageUrlSync(item)
          } else {
            item.imageUrl = ''
          }
        })
        this.handleProblemStatus = false
      }else if(tab.name !== 'second'){
        this.handleProblemStatus = true
      }
    },
    getSopProblemAndLayoutInfo() {
      const urlParams = new URLSearchParams(window.location.search);
      const wipOrderNo = urlParams.get('wipOrderNo');
      const param = {
        Inputs: {
          wipOrderNo
        }
      };
      if (wipOrderNo !== null) {
        getSopAndProblemList(param).then(res => {
          this.handleData(res.Outputs)
        })
      }
    },
    handleData(data) {
      const sopParam = JSON.parse(data.sopJson);
      const problemParam = JSON.parse(data.problemJson);
      const layoutParam = JSON.parse(data.layoutJson);
      this.appValue = data.token;
      this.handleSopParam(sopParam);
      this.handleProblemParam(problemParam);
      this.handleLayoutParam(layoutParam);
    },
    handleSopParam(param) {
      let idNum = 1;
      const newJson = {
        'label': param.wiporderno + '(' + param.productno + ')',
        'id': idNum++,
        'children': []
      };

      param.children.forEach(child => {
        const newData = {};
        newData.label = child.workcenter;
        newData.id = idNum++;
        newData.children = [];

        child.children.forEach(grandChild => {
          const innerData = {};
          innerData.label = grandChild.poname + '(' + grandChild.otname + ')';
          innerData.id = idNum++;
          innerData.children = [];

          grandChild.children.forEach(file => {
            const fileData = {}
            const fc = {}
            //this.getFileUrlSync(file.filecode, fileData,fc); // 同步获取文件预览链接
            //fileData.label = file.filecode + '(' + file.filename + ')';
            fileData.label = file.filename
            fileData.id = fc.id = idNum++
            fileData.filecode = fc.filecode = file.filecode
            innerData.children.push(fileData);
            this.filecodes.push(fc);
          });

          newData.children.push(innerData);
        });

        newJson.children.push(newData);
      });

      this.data2 = [newJson];
    },
    handleProblemParam(param) {
      this.wipOrderNo = param.wipOrderNo;
      this.productNo = param.productNo;
      this.modelNo = param.modelNo;

      param.children.forEach(children => {
        const problemData = {};
        problemData.description = children.description;
        problemData.note = children.note;
        problemData.imagePath = children.picture;
        problemData.imageUrlList = [];
        this.backendData.push(problemData);
      });
    },
    handleLayoutParam(param) {
      let idNum = 1;
      const wiporderno = {
        'label': param.wipOrderNo + '(' + param.productNo + ')',
        'id': idNum++,
        'children': []
      };
      param.productionLine.forEach((child) => {
        const prodLineData = {
          'label': child.productionLine+'(' + child.prdLineFileName + ')',
          'id': idNum++,
          'fileUrl': child.prdLineFileUrl,
          'children': []
        };
        child.station.forEach((child) => {
            const stationData = {
              'label': child.station + '(' + child.staFileName + ')',
              'id': idNum++,
              'fileUrl': child.staFileUrl,
              'children': []
            }
            prodLineData.children.push(stationData)
          })
        wiporderno.children.push(prodLineData)
      })
      this.layoutData = [wiporderno]
    },
    startResize(event) {
      this.startX = event.clientX;
      this.resizing = true;
      window.addEventListener('mousemove', this.resize);
      window.addEventListener('mouseup', this.stopResize);
    },
    resize(event) {
      if (this.resizing) {
        const offsetX = event.clientX - this.startX;
        this.sidebarWidth += offsetX;
        this.startX = event.clientX;
      }
    },
    stopResize() {
      this.resizing = false;
      window.removeEventListener('mousemove', this.resize);
      window.removeEventListener('mouseup', this.stopResize);
    },
    hideSidebar() {
      this.sidebarVisible = !this.sidebarVisible;
      if (this.sidebarVisible) {
        this.sidebarWidth = 300;
      } else {
        this.sidebarWidth = 65;
      }
    },
    handleCarouselInfo() {
      if (this.isCarousel) {
        if (this.carouselTime <= 0 || !Number.isInteger(this.carouselTime)) {
          this.carouselTime = 30;
        }
        this.intervalId = setInterval(() => {
          const currentIndex = this.filecodes.findIndex(file => file.filecode === this.tempFilecode);
          if (currentIndex === -1 || currentIndex === this.filecodes.length - 1) {
            //this.pdfUrl = this.filecodes[0].filecode;
            this.getFileUrlSync(this.filecodes[0].filecode)
            this.$refs.tree2.setCurrentKey(this.filecodes[0].id)
            this.tempFilecode = this.filecodes[0].filecode
          } else {
            //this.pdfUrl = this.filecodes[currentIndex + 1].filecode;
            this.getFileUrlSync(this.filecodes[currentIndex + 1].filecode)
            this.$refs.tree2.setCurrentKey(this.filecodes[currentIndex + 1].id)
            this.tempFilecode = this.filecodes[currentIndex + 1].filecode
          }
        }, 1000 * this.carouselTime);
        this.isCarousel = false;
        this.disabledVal = true;
        this.carouselInfo = "关闭轮播";
      } else {
        this.beforeDestroy();
        this.isCarousel = true;
        this.disabledVal = false;
        this.carouselInfo = "开启轮播";
      }
    },
    beforeDestroy() {
      clearInterval(this.intervalId);
    },
    handleToken(tempToken) {
      const storage = window.localStorage;
      return new Promise((resolve, reject) => {
        if (tempToken === null || tempToken === undefined) {
          getFileToken(this.appValue)
            .then(res => {
              const tmpToken = res.access_token;
              storage.setItem("access_token", tmpToken);
              resolve(tmpToken);
            })
            .catch(err => reject(err));
        } else if (tempToken === 'invalid_token') {
          getFileToken(this.appValue)
            .then(res => {
              const tmpToken = res.access_token;
              storage.access_token = tmpToken;
              resolve(tmpToken);
            })
            .catch(err => reject(err));
        } else {
          resolve(tempToken);
        }
      });
    },
    async getFileUrl(path) {
      const storage = window.localStorage;
      const tempToken = storage.getItem('access_token');
      await this.handleToken(tempToken);
      return this.getFileInfo(path); // 异步获取文件信息
    },
    handleFileUrl(neid) {
      const param = {
        'nsid': '1'
      };
      return new Promise((resolve, reject) => {
        getFileUrl(neid, param)
          .then(res => {
            if (res.errcode === 0) {
              resolve(res.previewUrl);
            } else {
              this.handleToken('invalid_token').then(() => {
                this.handleFileUrl(neid)
              })
            }
          })
          .catch(err => reject(err));
      });
    },
    getFileInfo(path) {
      const param = {
        'path': path,
        'path_type': 'ent'
      };
      return new Promise((resolve, reject) => {
        getFileInfo(param)
          .then(res => {
            if (res.errcode === 0) {
              resolve(this.handleFileUrl(res.neid)); // 同步获取文件预览链接
            } else {
              // 先执行handleToken
              this.handleToken('invalid_token').then(() => {
                this.getFileInfo(path)
              })
            }
          })
          .catch(err => reject(err));
      });

    },
    async getFileUrlSync(path) { //获取Sop路径
      try {
        this.pdfUrl = await this.getFileUrl(path);
      } catch (err) {
        console.error(err);
      }
    },
    async getProblemImageUrlSync(item) {
      try {
        const previewUrl = await this.getFileInfo(item.imagePath)
        item.imageUrl = previewUrl;
        item.imageUrlList.push(previewUrl);
      } catch (err) {
        console.error(err);
      }
    },
    async getLayoutUrlSync(path){
      try {
        this.layoutUrl = await this.getFileUrl(path);
      } catch (err) {
        console.error(err);
      }
    }
  }

}
</script>

<style>
.app-container {
  height: 100%;
  position: relative;
  padding-top: 0px;
}

.resizable-sidebar {
  overflow-y: auto; /* 设置侧边栏上下滚动 */
  position: relative;
  border-radius: 4px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
}

.resize-handle {
  position: absolute;
  top: 0;
  right: -5px; /* 调整按钮位置 */
  width: 10px; /* 调整按钮大小 */
  height: 100%;
  cursor: col-resize;
  background-color: #f0f0f0;
}

.sidebar-header {
  display: flex;
  align-items: center;
}

.hide-sidebar-icon {
  margin-right: 10px;
  cursor: pointer;
}

.el-aside .el-input {
  margin-bottom: 10px;
}

.el-tree {
  overflow: hidden;
}

.image-content {
  max-width: 98%;
  height: 77vh;
}

.text-content {
  max-width: 95%;
  white-space: pre-line;
  word-wrap: break-word;
  word-break: break-all;
  padding-left: 30px;
}

.label-container {
  display: flex;
  margin-top: 5px;
  margin-bottom: 5px;
  flex-direction: column;
}

.custom-label {
  width: 120px;
  padding-left: 30px;
  padding-right: 15px;
  font-size: medium;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #E4E7ED !important;
}

.el-header-content {
  height: 40px !important;
  padding-left: 3%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
}

.el-header-container {
  margin-left: 2%;
  font-size: 25px;
}

.el-main-header {
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  height: 82vh;
  padding-top: 0;
}

.sidebar-tree-wrapper {
  max-height: 70vh; /* 设置树形结构最大高度 */
  overflow-y: auto; /* 设置树形结构上下滚动 */
  /* 添加其他样式 */
}

.problem-content {
  background-image: -webkit-gradient(linear, left top, right top, from(#f5f7fa), to(#e4e7ed));
  background-size: cover;
  border-radius: 20px;
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  margin: 25px 0 25px 0;
}

.problem-leftContent{
  width: 27%;
  display: grid;
  flex-direction: column;
}

.el-form-item{
  margin-top: 5px!important;
  margin-bottom: 5px!important;
}

.el-form-item__content{
  line-height: 25px;
}


</style>
